package com.geek.water.controller;

import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.geek.water.constant.CodeConstant;
import com.geek.water.constant.MessageConstant;
import com.geek.water.entity.PaymentRecord;
import com.geek.water.exception.WaterException;
import com.geek.water.result.Result;
import com.geek.water.service.PaymentRecordService;
import com.geek.water.vo.PageQueryVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import javax.validation.constraints.Min;
import java.time.LocalDateTime;

@RestController
@RequestMapping("/admin/payment")
@RequiredArgsConstructor
@Api(tags = "后台系统-支付记录管理")
@Slf4j
@Validated
public class PaymentRecordController {

    private final PaymentRecordService paymentRecordService;

    @ApiOperation("分页查询支付记录")
    @GetMapping("/page")
    public Result listPayments(
            @ApiParam("当前页，最小 1，默认 1")
            @RequestParam(value = "currentPage", defaultValue = "1")
            @Min(value = 1, message = "currentPage 最小为 1")
            Integer currentPage,

            @ApiParam("每页大小，最小 1，默认 10")
            @RequestParam(value = "pageSize", defaultValue = "10")
            @Min(value = 1, message = "pageSize 最小为 1")
            Integer pageSize,

            @ApiParam("账单 ID，可选")
            @RequestParam(value = "billId", required = false)
            Long billId,

            @ApiParam("开始时间，格式 yyyy-MM-dd HH:mm:ss，可选")
            @RequestParam(value = "startTime", required = false)
            @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
            LocalDateTime startTime,

            @ApiParam("结束时间，格式 yyyy-MM-dd HH:mm:ss，可选")
            @RequestParam(value = "endTime", required = false)
            @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
            LocalDateTime endTime
    ) {
        try {
            PageQueryVO pageQuery = new PageQueryVO();
            pageQuery.setCurrentPage(currentPage);
            pageQuery.setPageSize(pageSize);

            Page<PaymentRecord> page = paymentRecordService.listPayments(pageQuery, billId, startTime, endTime);
            if (page != null && !CollectionUtils.isEmpty(page.getRecords())) {
                return new Result(CodeConstant.SUCCESS, MessageConstant.QUERY_PAYMENT_SUCCESS, page);
            }
            return new Result(CodeConstant.FAIL, MessageConstant.QUERY_PAYMENT_FAIL);
        } catch (Exception ex) {
            log.error("分页查询支付记录异常", ex);
            return new Result(CodeConstant.FAIL, MessageConstant.INTERNAL_ERROR);
        }
    }

    @ApiOperation("创建支付记录")
    @PostMapping
    public Result createPayment(
            @ApiParam("支付记录实体")
            @Valid @RequestBody
            PaymentRecord paymentRecord
    ) {
        try {
            boolean ok = paymentRecordService.recordPayment(paymentRecord);
            if (ok) {
                return new Result(CodeConstant.SUCCESS, MessageConstant.RECORD_PAYMENT_SUCCESS);
            } else {
                return new Result(CodeConstant.FAIL, MessageConstant.RECORD_PAYMENT_FAIL);
            }
        } catch (WaterException we) {
            log.warn("创建支付记录业务校验失败: {}", we.getMessage());
            return new Result(CodeConstant.FAIL, we.getMessage());
        } catch (Exception ex) {
            log.error("创建支付记录异常", ex);
            return new Result(CodeConstant.FAIL, MessageConstant.INTERNAL_ERROR);
        }
    }

    @ApiOperation("获取支付详情")
    @GetMapping("/{id}")
    public Result getPaymentDetail(
            @ApiParam("支付记录 ID")
            @PathVariable
            @Min(value = 1, message = "id 最小为 1")
            Long id
    ) {
        try {
            PaymentRecord record = paymentRecordService.getById(id);
            if (record != null) {
                return new Result(CodeConstant.SUCCESS, MessageConstant.QUERY_PAYMENT_SUCCESS, record);
            }
            return new Result(CodeConstant.FAIL, MessageConstant.PAYMENT_NOT_EXIST);
        } catch (Exception ex) {
            log.error("获取支付详情异常", ex);
            return new Result(CodeConstant.FAIL, MessageConstant.INTERNAL_ERROR);
        }
    }

    @ApiOperation("更新支付记录")
    @PutMapping("/{id}")
    public Result updatePayment(
            @ApiParam("支付记录 ID")
            @PathVariable
            @Min(value = 1, message = "id 最小为 1")
            Long id,

            @ApiParam("支付记录实体，ID 会被覆盖")
            @Valid @RequestBody
            PaymentRecord paymentRecord
    ) {
        try {
            paymentRecord.setId(id);
            boolean ok = paymentRecordService.updateById(paymentRecord);
            if (ok) {
                return new Result(CodeConstant.SUCCESS, MessageConstant.RECORD_PAYMENT_SUCCESS);
            }
            return new Result(CodeConstant.FAIL, MessageConstant.RECORD_PAYMENT_FAIL);
        } catch (Exception ex) {
            log.error("更新支付记录异常", ex);
            return new Result(CodeConstant.FAIL, MessageConstant.INTERNAL_ERROR);
        }
    }

    @ApiOperation("删除支付记录")
    @DeleteMapping("/{id}")
    public Result deletePayment(
            @ApiParam("支付记录 ID")
            @PathVariable
            @Min(value = 1, message = "id 最小为 1")
            Long id
    ) {
        try {
            boolean ok = paymentRecordService.removeById(id);
            if (ok) {
                return new Result(CodeConstant.SUCCESS, MessageConstant.RECORD_PAYMENT_SUCCESS);
            }
            return new Result(CodeConstant.FAIL, MessageConstant.RECORD_PAYMENT_FAIL);
        } catch (Exception ex) {
            log.error("删除支付记录异常", ex);
            return new Result(CodeConstant.FAIL, MessageConstant.INTERNAL_ERROR);
        }
    }
}
